﻿/*+===================================================================
File:      Grenade.cpp

Summary:   Định nghĩa các phương thức của CGrenade.
===================================================================+*/

#include "Grenade.h"
#include "Explosion.h"
#include "PlayState.h"

#define VX 50.0f
#define VY 250.0f
#define AY -400.0f

CGrenade::CGrenade(D3DXVECTOR2 pos, int id, int typeID) : CMoveableObject(pos, id, typeID)
{
	CResourcesManager::GetInstance()->GetSprite(ID_SPRITE_GRENADE);
	m_pSprite = m_pResourceManager->GetSprite(ID_SPRITE_GRENADE);

	m_a.y = AY;
	m_v.x = VX;
	m_v.y = VY;

	m_posInit = pos;
	m_fRotateAngle = 0.0f;

	m_box.width = 8.0f;
	m_box.height = 28.0f;
}

CGrenade::~CGrenade()
{

}

void CGrenade::Update(float timeFrame)
{
	if (!m_bIsLive)
		return;

	if (m_bIsExplode)
	{
		if (m_fTimeExplode > 0)
			m_fTimeExplode -= timeFrame;
		else
		{
			m_fTimeExplode = 0.0f;
			m_bIsExplode = false;

			m_a.y = AY;
			m_v.x = VX;
			m_v.y = VY;
			m_pos = m_posInit;
			m_fRotateAngle = 0.0f;
		}
	}
	else
	{
		// Hiệu ứng xoay.
		if (m_fTimeRotate > 0)
			m_fTimeRotate -= timeFrame;
		else
		{
			m_fTimeRotate = 0.08f;
			m_fRotateAngle += 45.0f;
		}
	}

	UpdateBox(timeFrame);
}

void CGrenade::UpdateCollision(vector<CGameObject*> vecGameObjs, float timeFrame)
{
	if (!m_bIsLive || m_bIsExplode)
		return;

	

	float timeCollision = timeFrame;
	float normalx = 0.0f, normaly = 0.0f;
	CGameObject* objCollision = NULL; // Đối tượng va chạm sớm nhất.

	for (int i = 0; i < vecGameObjs.size(); i++)
	{
			float t = CheckCollision(vecGameObjs[i], normalx, normaly, timeFrame);
			if (t < timeFrame)
			{
				switch (vecGameObjs[i]->GetTypeId())
				{
					case ID_GRASS_CAN_FALL:
					case ID_GRASS:
						if (normaly == 1.0f)
						{
							objCollision = vecGameObjs[i];
							timeCollision = t;
						}
						break;
				}
			}
	}

	// Xử lí va chạm
	if (objCollision != NULL)
	{
		m_pos += m_v * timeCollision;
		m_v.x = 0.0f;
		m_v.y = 0.0f;
		m_a.x = 0.0f;
		m_a.y = 0.0f;

		this->Explode();
	}

	m_pos += m_v * timeFrame;
	m_v += m_a* timeFrame;
}

void CGrenade::Draw()
{
	if (!m_bIsLive || m_bIsExplode)
		return;

	D3DXVECTOR2 pos = CViewport::GetInstance()->TransformMatrix(m_pos);
	m_pSprite->Draw(pos, (m_fRotateAngle * PI) / 180.0f);
}

void CGrenade::Explode()
{
	m_bIsExplode = true;
	m_fTimeExplode = 0.45f;

	CExplosion* ex = new CExplosion(m_pos, 0, ID_ENEMY_EXPLOSION, true);
	CPlayState::s_objsOutSideQuadTree.push_back(ex);
}